package com.shundr.shipper.truck;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult.AddressComponent;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.shundr.shipper.R;
import com.shundr.shipper.base.BaseActivity;
import com.shundr.shipper.common.AreaGridActivity;
import com.shundr.shipper.common.adapter.ExpectedFlowAdapter;
import com.shundr.shipper.common.adapter.ExpectedFlowAdapter.DeleteListener;
import com.shundr.shipper.common.model.AreaInfo;
import com.shundr.shipper.common.model.AttributeInfo;
import com.shundr.shipper.common.model.PictureInfo;
import com.shundr.shipper.common.util.AllCapTransfMethod;
import com.shundr.shipper.common.util.AreaUtils;
import com.shundr.shipper.common.util.AttrUtil;
import com.shundr.shipper.common.util.BaiduMapManager;
import com.shundr.shipper.common.util.Base64Util;
import com.shundr.shipper.common.util.JsonUtil;
import com.shundr.shipper.common.util.LImageLoader;
import com.shundr.shipper.common.util.PictureUtil;
import com.shundr.shipper.common.util.PrefConstants;
import com.shundr.shipper.common.util.PrefUtils;
import com.shundr.shipper.common.util.ProgressDialogHelper;
import com.shundr.shipper.common.util.ToastHelper;
import com.shundr.shipper.common.view.DialogChoiceLength;
import com.shundr.shipper.common.view.DialogChoiceLength.OnSelectListener;
import com.shundr.shipper.common.view.DialogChoiceTruckInfo;
import com.shundr.shipper.common.view.DialogChoiceTruckInfo.OnChoiceListener;
import com.shundr.shipper.common.view.ListViewForScrollView;
import com.shundr.shipper.frame.constant.LConstants;
import com.shundr.shipper.frame.constant.LContext;
import com.shundr.shipper.frame.http.LHttpRequest;
import com.shundr.shipper.frame.util.LLogger;
import com.shundr.shipper.frame.util.StringUtil;
import com.shundr.shipper.truck.http.UserTruckRequest;
import com.shundr.shipper.truck.model.TruckInfo;

/**
 * 添加车辆
 * AddTruckActivity
 * 
 * @author larry 2015-4-27 下午2:30:31 
 * @version 1.0.0
 *
 */
public class UpdateTruckActivity extends BaseActivity implements OnClickListener{
	
	private TextView tvTruckNum;
	private Button btnPCode;//省份代号
	private EditText etTruckNum;//车牌号码
	private Button btnTruckType;//车辆类型
	private EditText etTruckLoad;//载重
	private Button btnTruckLength;//长度
	
	private Button btnDirect;//流向
	
	private Button btnSave;//保存
	
	private String pType;//车辆类型
	
	private ImageView ivFull;//车辆照片
	private ImageView ivDriverCard;//行驶证
	
	private TextView tvTruckPicSample;//车辆照片示例
	private TextView tvTravelpicSample;//行驶证照片示例
	
	private PictureInfo mPTruckInfo;//车辆照片
	private PictureInfo mPLisInfo;//行驶证
	
	private List<PictureInfo> mPictures = new ArrayList<PictureInfo>();
	private int flag= 0;
	public static final int NONE = 0;
	public static final int PHOTOHRAPH = 1;// 拍照
	public static final int PHOTOZOOM = 2; // 缩放
	public static final int PHOTORESOULT = 3;// 结果
	public static final String IMAGE_UNSPECIFIED = "image/*";
	
	private BaiduMapManager mMapManager;
	
	private double mLng;
	private double mLat;
	private String mAddressCode = "";
	
	private List<AreaInfo> mAreas = new ArrayList<AreaInfo>();
	private ListViewForScrollView mListView;
	private ExpectedFlowAdapter mAdapter;
	
	private TruckInfo mInfo;
	
	private Handler handler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			try {
				String description=(String)msg.obj;
				switch (msg.what) {
				case UserTruckRequest.UPDATE_TRUCK_SUCCESSED:
					ProgressDialogHelper.dismiss();
					ToastHelper.toastShort(mContext, description);
					new Timer().schedule(new TimerTask() {
						
						@Override
						public void run() {
							setResult(888);
							finish();
						}
					}, 1000);
					break;
				case LHttpRequest.REQUEST_FAILED:
					ProgressDialogHelper.dismiss();
					ToastHelper.toastShort(mContext, description);
					break;
				default:
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			super.handleMessage(msg);
		}
		
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_update_truck);
		initView();
		String json = getIntent().getStringExtra("json");
		mInfo = JsonUtil.fromJson(json, TruckInfo.class);
		initData();
		mMapManager = new BaiduMapManager(mContext, null);
		mMapManager.initMap();
		mMapManager.setLocationListener(new MyLocationListenner());
		mMapManager.startLocation();
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putSerializable("mPTruckInfo", mPTruckInfo);
		outState.putSerializable("mPLisInfo", mPLisInfo);
		outState.putInt("flag", flag);
		outState.putString("pType", pType);
		
		outState.putDouble("mLng", mLng);
		outState.putDouble("mLat", mLat);
		outState.putString("mAddressCode", mAddressCode);
		
		outState.putString("json", JsonUtil.toJson(mAreas).toString());
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mPTruckInfo = (PictureInfo) savedInstanceState.getSerializable("mPTruckInfo");
		
		if (mPTruckInfo != null) {
			ImageLoader.getInstance().displayImage("file://" + mPTruckInfo.getFilename(), ivFull,LImageLoader.mOptions);
		}
		mPLisInfo = (PictureInfo) savedInstanceState.getSerializable("mPLisInfo");
		
		if (mPLisInfo != null) {
			ImageLoader.getInstance().displayImage("file://" + mPLisInfo.getFilename(), ivDriverCard,LImageLoader.mOptions);
		}
		flag = savedInstanceState.getInt("flag");
		pType = savedInstanceState.getString("pType");
		
		mLng = savedInstanceState.getDouble("mLng");
		mLat = savedInstanceState.getDouble("mLat");
		mAddressCode = savedInstanceState.getString("mAddressCode");
		String json = savedInstanceState.getString("json");
		mAreas = (List<AreaInfo>)JsonUtil.getList(json, AreaInfo.class);
		initAdapter();
	}
	
	private void initAdapter(){
		mListView = (ListViewForScrollView)findViewById(R.id.lv_list);
		mAdapter = new ExpectedFlowAdapter(mContext, mAreas);
		mListView.setAdapter(mAdapter);
		mAdapter.setDeleteListener(new DeleteListener() {
			
			@Override
			public void onDelete(int position) {
				mAreas.remove(position);
				mAdapter.notifyDataSetChanged();
				initButton();
			}
		});
	}
	
	private void initView(){
		tvTruckNum = (TextView)findViewById(R.id.tv_truck_num);
		btnPCode=(Button)findViewById(R.id.btn_province_code);
		etTruckNum=(EditText)findViewById(R.id.et_truck_num);		
		etTruckNum.setTransformationMethod(new AllCapTransfMethod());
		btnTruckType=(Button)findViewById(R.id.btn_truck_type);
		etTruckLoad=(EditText)findViewById(R.id.et_truck_load);
		btnTruckLength=(Button)findViewById(R.id.btn_truck_leng);
		btnDirect=(Button)findViewById(R.id.btn_truck_direction);
		btnSave = (Button)findViewById(R.id.btn_save);
		tvTruckPicSample=(TextView)findViewById(R.id.tv_truck_image);
		tvTravelpicSample=(TextView)findViewById(R.id.tv_travel_image);
		
		ivFull = (ImageView)findViewById(R.id.iv_car_full);
		ivDriverCard = (ImageView)findViewById(R.id.iv_driver);
		tvTruckPicSample.setVisibility(View.VISIBLE);
		tvTravelpicSample.setVisibility(View.VISIBLE);
		
		tvTruckPicSample.setOnClickListener(this);
		tvTravelpicSample.setOnClickListener(this);
		btnPCode.setOnClickListener(this);
		btnTruckType.setOnClickListener(this);
		btnTruckLength.setOnClickListener(this);
		btnDirect.setOnClickListener(this);
		ivFull.setOnClickListener(this);
		ivDriverCard.setOnClickListener(this);
		btnSave.setOnClickListener(this);
		
		initAdapter();
	}
	
	private void initButton(){
		if(mAreas.size() == 4){
			btnDirect.setBackgroundResource(R.drawable.btn_gray_light_selector);
			btnDirect.setClickable(false);
		}else{
			btnDirect.setBackgroundResource(R.drawable.btn_green_light_selector);
			btnDirect.setClickable(true);
		}
	}
	
	private void initData(){
		if(mInfo == null){
			return;
		}
		tvTruckNum.setText(mInfo.getTruckPlateNumber());
		ImageLoader.getInstance().displayImage(mInfo.getTruckPic(), ivFull, LImageLoader.mOptions);
		ImageLoader.getInstance().displayImage(mInfo.getTruckLicensePic(), ivDriverCard, LImageLoader.mOptions);
		btnTruckType.setText(mInfo.getTruckType());
		pType = mInfo.getTruckTypeCode() + "";
		etTruckLoad.setText(mInfo.getTruckCapacity());
		btnTruckLength.setText(mInfo.getTruckLength());
		if(!StringUtil.isNull(mInfo.getTruckForwardCity1())){
			mAreas.add(new AreaInfo(mInfo.getTruckForwardCity1(), mInfo.getTruckForwardCity1Code() + ""));
		}
		if(!StringUtil.isNull(mInfo.getTruckForwardCity2())){
			mAreas.add(new AreaInfo(mInfo.getTruckForwardCity2(), mInfo.getTruckForwardCity2Code() + ""));
		}
		if(!StringUtil.isNull(mInfo.getTruckForwardCity3())){
			mAreas.add(new AreaInfo(mInfo.getTruckForwardCity3(), mInfo.getTruckForwardCity3Code() + ""));
		}
		if(!StringUtil.isNull(mInfo.getTruckForwardCity4())){
			mAreas.add(new AreaInfo(mInfo.getTruckForwardCity4(), mInfo.getTruckForwardCity4Code() + ""));
		}
		mAdapter.notifyDataSetChanged();
		initButton();
	}
	
	@Override
	public void onClick(View v) {
		Intent start;
		switch (v.getId()) {
		case R.id.btn_province_code:
			DialogChoiceTruckInfo choiceTruckNum = new DialogChoiceTruckInfo(
					mContext, "选择车牌", AttrUtil.TYPE_PROVINCE_SHORT,
					new OnChoiceListener() {

						@Override
						public void selected(AttributeInfo info) {
							try {
								btnPCode.setText(info.getName());
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					});
			choiceTruckNum.show();
			break;
		case R.id.iv_car_full:
			flag= 0 ;
			PictureUtil.doPickPhotoAction(this);
			break;
		case R.id.iv_driver:
			flag = 1;
			PictureUtil.doPickPhotoAction(this);
			break;
		case R.id.btn_truck_type:
			DialogChoiceTruckInfo choiceTruckType = new DialogChoiceTruckInfo(mContext, "选择车辆类型", AttrUtil.TYPE_TRUCK, new OnChoiceListener() {
				
				@Override
				public void selected(AttributeInfo info) {
					try {
						btnTruckType.setText(info.getName());
						pType=info.getCode();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
			choiceTruckType.show();
			break;
		case R.id.btn_truck_leng:
			DialogChoiceLength length = new DialogChoiceLength(mContext, "选择车辆长度", new OnSelectListener() {
				
				@Override
				public void selected(AttributeInfo info) {
					try {
						btnTruckLength.setText(info.getCode());
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
			length.show();
			break;
		case R.id.btn_truck_direction:
			start = new Intent(mContext, AreaGridActivity.class);
			start.putExtra("title", "期望流向");
			startActivityForResult(start, 502);
			break;
		case R.id.btn_save:
			saveTruckInfo();
			break;
		case R.id.tv_truck_image:
//			DialogPicSample dialogPicSample=new DialogPicSample(mContext, R.drawable.truck_pic_sample);
//			dialogPicSample.show();
			break;
		case R.id.tv_travel_image:
//			DialogPicSample dialogPicSample1=new DialogPicSample(mContext, R.drawable.travel_pic_sample);
//			dialogPicSample1.show();
			break;
		default:
			break;
		}
		
	}
	
	private void saveTruckInfo() {
		try {
//			if(mPTruckInfo == null){
//				ToastHelper.toastShort(mContext, "请上传车辆照片");
//				return;
//			}
//			if(mPLisInfo == null){
//				ToastHelper.toastShort(mContext, "请上传车辆行驶证照片");
//				return;
//			}
			String truckType=btnTruckType.getText().toString();
			if(StringUtil.isNull(truckType)){
				ToastHelper.toastShort(mContext, "请选择车辆类型");
				return;
			}
			String weight=etTruckLoad.getText().toString();
			if(StringUtil.isNull(weight)){
				ToastHelper.toastShort(mContext, "请填写车辆载重");
				return;
			}
			if(weight.equals("0")||weight.equals("0.0")){
				ToastHelper.toastShort(mContext, "车辆载重不能为0");
				return;
			}
			String length=btnTruckLength.getText().toString();
			if(StringUtil.isNull(length)){
				ToastHelper.toastShort(mContext, "请填写车辆长度");
				return;
			}
			if(length.equals("0")||length.equals("0.0")){
				ToastHelper.toastShort(mContext, "车辆载重不能为0");
				return;
			}
			String directStr = "";
			String directCode = "";
			if(mAreas.size() > 0){
				for(AreaInfo info : mAreas){
					directStr = directStr + info.getName() + "-";
					directCode = directCode + info.getCode() + "-";
				}
				directStr = directStr.substring(0, directStr.length() - 1);
				directCode = directCode.substring(0, directCode.length() - 1);
			}
			mPictures.clear();
			if(mPTruckInfo != null){
				mPictures.add(mPTruckInfo);
			}
			if(mPLisInfo != null){
				mPictures.add(mPLisInfo);
			}
			String json = JsonUtil.toJson(mPictures);
			ProgressDialogHelper.show(mContext);
			new UserTruckRequest(mContext, handler).updateTruck(
					mInfo.getTruckId() + "", pType, etTruckLoad.getText()
							.toString(), btnTruckLength.getText().toString(),
					directStr, directCode, mLng, mLat, LContext.mAddress, mAddressCode,
					json);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private boolean isFirstLoc = true;// 是否首次定位
	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null)
				return;
			if (isFirstLoc) {
				// isFirstLoc = false;
				// 获取当前位置的经纬度
				LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
				LLogger.e("维度 ： " + location.getLatitude() + "\n" + "经度  : " + location.getLongitude());
				mLng = location.getLongitude();
				mLat = location.getLatitude();
				mMapManager.setGeoCoderResultListener(new MyGeoCoderListener());
				mMapManager.reverseLocation(latLng);
			}

		}
		public void onReceivePoi(BDLocation poiLocation) {

		}
	}

	public class MyGeoCoderListener implements OnGetGeoCoderResultListener {

		@Override
		public void onGetGeoCodeResult(GeoCodeResult result) {
			if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
				ToastHelper.toastShort(mContext, "定位失败");
			} else {
				ToastHelper.toastShort(mContext, result.getAddress());
			}
		}

		@Override
		public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
			if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
				ToastHelper.toastShort(mContext, "定位失败");
			} else {
				AddressComponent component = result.getAddressDetail();
				String mAddress = component.province
						+ component.city + component.district
						+ component.street + component.streetNumber;
				try {
					AreaInfo start = AreaUtils.getAreaInfo(component.province, component.city,component.district);
					mAddressCode = start.getCode();
					PrefUtils.setPrefString(mContext, PrefConstants.SRC_PLACE, component.province + start.getName());
					PrefUtils.setPrefString(mContext, PrefConstants.SRC_CODE,mAddressCode);
//					ToastHelper.toastShort(mContext, mAddress);
					LContext.mAddress = mAddress;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}
	
	@Override
	public void onPause() {
		mMapManager.stop();
		super.onPause();
	}
	
	@Override
	public void onDestroy() {
		mMapManager.destroy();
//		releaseImageView(ivFull);
//		releaseImageView(ivDriverCard);
		super.onDestroy();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {		
		if (resultCode == RESULT_OK) {
			try {
				Uri data2 = null;
				if (data == null) {
					data2 = PictureUtil.getImageUri();
				} else {
					data2 = data.getData();
				}
				String outPic = "";
				switch (requestCode) {
				case PictureUtil.PHOTO_PICKED_WITH_DATA:
					outPic = PictureUtil.getRealFilePath(mContext, data2);
					outPic = PictureUtil.compressJpgImage(outPic);
					break;
				case PictureUtil.CAMERA_WITH_DATA:
					outPic = PictureUtil.compressJpgImage(LConstants.TEMP_PIC_PATH);
					break;
				case PictureUtil.PHOTO_CROP:
					break;
				default:
					break;
				}
				
				if (!new File(outPic).exists()) {
					ToastHelper.toastShort(mContext, getResources().getString(R.string.image_error));
					return;
				}
				
				Bitmap bitmap = BitmapFactory.decodeFile(outPic);
				PictureInfo info = new PictureInfo();
				info.setFileBase64Body(Base64Util.encodeImage(bitmap));
				info.setFilename(outPic);
				bitmap.recycle();
				if (flag == 0) {
					info.setType(PictureInfo.FileType.truck);
					mPTruckInfo = info;
					ImageLoader.getInstance().displayImage("file://" + outPic, ivFull, LImageLoader.mOptions);
				} else if (flag == 1) {
					info.setType(PictureInfo.FileType.truck_license);
					mPLisInfo = info;
					ImageLoader.getInstance().displayImage("file://" + outPic, ivDriverCard, LImageLoader.mOptions);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if(requestCode==502){
			if(data != null){
				try {
					String json = data.getStringExtra("json");
					List<AreaInfo> areas = JsonUtil.getList(json, AreaInfo.class);
					if(areas.size() > 0){
						if(StringUtil.isNull(areas.get(0).getCode())){
							ToastHelper.toastShort(mContext, "请选择具体城市");
							return ;
						}
						for(AreaInfo info : mAreas){
							if(StringUtil.isEqual(info.getCode(), areas.get(0).getCode())){
								ToastHelper.toastShort(mContext, "该城市已添加,请重新选择");
								return;
							}
						}
					}
					mAreas.addAll(areas);
					mAdapter.notifyDataSetChanged();
					initButton();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.menu_confirm, menu);
		menu.getItem(0).setTitle("保存");
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_confirm:
			saveTruckInfo();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

}
